<template>
  <div class="enterpriseEdit-container-padding">
    <el-form
      :inline="true"
      :model="formInline"
      class="form-inline"
      label-width="auto"
    >
      <el-form-item
        v-for="(item, index) in formList"
        :key="index"
        :label="item.label"
      >
        <!-- select -->
        <el-select
          v-if="item.type === 'select'"
          v-model="formInline[item.prop]"
          placeholder="请选择"
        >
          <el-option
            v-for="j in item.options"
            :key="j.value"
            :label="j.label"
            :value="j.value"
          />
        </el-select>

        <!-- date -->
        <el-date-picker
          v-if="item.type === 'date'"
          v-model="formInline[item.prop]"
          type="daterange"
          range-separator="→"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          clearable
        />

        <!-- tree -->
        <el-tree-select
          v-if="item.type === 'tree'"
          v-model="formInline[item.prop]"
          :data="item.options"
          :render-after-expand="false"
        />
      </el-form-item>
      <el-form-item label="关键字：">
        <div class="keyword">
          <el-select
            v-model="formInline.check"
            placeholder="请选择"
            style="width: 100px"
          >
            <el-option
              v-for="j in valueoptions"
              :key="j.value"
              :label="j.label"
              :value="j.value"
            />
          </el-select>
          <el-input v-model="formInline.inputValue" />
        </div>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          style="margin-right: 10px"
          @click="handSearch"
        >
          搜索
        </el-button>
        <el-button @click="handReset">重置</el-button>
      </el-form-item>
    </el-form>
    <el-divider />
    <div class="buttonList">
      <el-button type="primary" @click="handAddPatent">
        企业标准修改单上报
      </el-button>
      <el-button :loading="downLoading" @click="handExport">
        导出搜索结果
      </el-button>
    </div>
    <vxe-grid v-bind="gridOptions" :height="height">
      <!-- <template #sex_default="{ row }">
        <span>{{ row.sex === '1' ? '男' : '女' }}</span>
      </template> -->
      <template #operate="{ row }">
        <el-button type="primary" link @click="viewEvent(row, 1)">
          详情
        </el-button>
        <!-- <el-button type="primary" link @click="viewEvent(row, 2)">
          修改
        </el-button>
        <el-button type="danger" link @click="del(row)">删除</el-button> -->
      </template>
      <template #pager>
        <!--使用 pager 插槽-->
        <vxe-pager
          v-model:current-page="tablePage.currentPage"
          v-model:page-size="tablePage.pageSize"
          :layouts="[
            'Sizes',
            'PrevJump',
            'PrevPage',
            'Number',
            'NextPage',
            'NextJump',
            'FullJump',
            'Total',
          ]"
          :total="tablePage.total"
          @page-change="handlePageChange"
        />
      </template>
    </vxe-grid>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted } from 'vue'
  import { gridOptions, formList, valueoptions } from './table/column'
  import { useRouter } from 'vue-router'
  import { VxePagerEvents } from 'vxe-table'
  import {
    getEnterpriseEditList,
    getEnterpriseEditExport,
    deleteEnterpriseEdit,
  } from '@/api/standard/enterpriseEdit'
  import { getSimpleDeptList } from '@/api/system/dept'
  import { useDownload } from '@/utils/useDownload'
  import { useAchievementAwardStore } from '@/store/modules/achievementAward'
  import { useDictStore } from '@/store/modules/dict'
  const dictStore = useDictStore()

  const router = useRouter()
  // 搜索表单
  const formInline = ref({
    check: '',
    inputValue: '',
  })
  // 搜索
  const handSearch = () => {
    if (formInline.value.inputValue != '' && formInline.value.check == '') {
      ElMessage.warning('请选择搜索类型')
      return
    }
    formInline.value[formInline.value.check] = formInline.value.inputValue
    getList()
  }
  // 重置搜索
  const handReset = () => {
    formInline.value = { check: '', inputValue: '' }
    formList.value.forEach((item) => {
      formInline.value[item.prop] = ''
    })
  }

  const getDptList = () => {
    getSimpleDeptList().then((res: any) => {
      const list = []
      res.data.forEach((item) => {
        list.push({
          label: item.name,
          value: item.id,
        })
      })
      store.setDeptList(list)
      return list
    })
  }

  const store = useAchievementAwardStore()
  const { DeptList } = storeToRefs(store)
  const departmentOptions = computed(() => {
    return DeptList.value.length == 0 ? getDptList() : DeptList.value
  })

  const validProps = new Set([
    'status',
    'standardType',
    'belongProfession',
    'draftUnitName',
  ])
  const propToOptionsMap = {
    status: computed(() =>
      dictStore.getDictType('enterprise_standard_flow_status')
    ),
    standardType: [],
    belongProfession: [],
    draftUnitName: departmentOptions,
  }

  formList.value.forEach((item) => {
    if (validProps.has(item.prop)) {
      item.options = propToOptionsMap[item.prop]
    }
  })

  // 导出搜索结果
  const { downLoading, downloadFile } = useDownload(
    getEnterpriseEditExport,
    '企业标准修改单.xls'
  )
  const handExport = async () => {
    await downloadFile(formInline.value)
  }

  const handAddPatent = () => {
    router.push('/standard/enterpriseEdit/add')
  }

  const viewEvent = (row: any, type: number) => {
    if (type == 1) {
      router.push('/standard/enterpriseEdit/details')
    }
  }

  const getList = () => {
    const obj = Object.assign({}, formInline.value)
    delete obj.check
    delete obj.inputValue
    const params = {
      pageNo: tablePage.currentPage,
      pageSize: tablePage.pageSize,
      ...obj,
    }
    getEnterpriseEditList(params).then((res) => {
      const { data } = res
      gridOptions.data = data.list
      tablePage.total = data.total
    })
  }

  onMounted(async () => {
    getList()
  })

  const tablePage = reactive({
    total: 0,
    currentPage: 1,
    pageSize: 10,
  })

  const handlePageChange: VxePagerEvents.PageChange = ({
    currentPage,
    pageSize,
  }) => {
    tablePage.currentPage = currentPage
    tablePage.pageSize = pageSize
    // findList()
  }

  const del = (row: any) => {
    ElMessageBox.confirm('确定删除该条专利?', '删除专利', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(() => {
        ElMessage({
          type: 'success',
          message: 'Delete completed',
        })
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: 'Delete canceled',
        })
      })
  }
  const height = ref(0)
  const $baseTableHeight = inject<any>('$baseTableHeight')
  onBeforeMount(() => {
    window.addEventListener('resize', handleHeight)
  })

  onBeforeUnmount(() => {
    window.removeEventListener('resize', handleHeight)
  })

  const handleHeight = () => {
    height.value = $baseTableHeight(0)
  }
</script>

<style scoped lang="scss">
  .buttonList {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
  }
  :deep(.el-divider) {
    margin: 8px 0 20px 0 !important;
  }

  .form-inline {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    grid-column-gap: 20px;
    :deep(.el-form-item) {
      margin-left: 0;
      margin-right: 0;
    }
  }
  .keyword {
    display: flex;
    align-items: center;
  }
</style>
